package cn.edu.baiyunu.myapplication.ui.screens.add

import androidx.activity.compose.BackHandler
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Category
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.Notes
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import cn.edu.baiyunu.myapplication.ui.screens.add.components.AmountKeyboard
import cn.edu.baiyunu.myapplication.ui.screens.add.components.KeyboardItem

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BasicAddTransactionScreen(
    viewModel: AddTransactionViewModel = viewModel(),
    onNavigateUp: () -> Unit,
    navigateToSelectCategory: () -> Unit,
) {
    val uiState by viewModel.uiState.collectAsState()
    var showKeyboard by remember { mutableStateOf(false) }

    BackHandler {
        if (showKeyboard) {
            showKeyboard = false
        } else {
            onNavigateUp()
        }
    }

    Box(modifier = Modifier.fillMaxSize()) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(MaterialTheme.colorScheme.background)
        ) {
            // 顶部栏
            CenterAlignedTopAppBar(
                title = { Text("添加交易") },
                navigationIcon = {
                    IconButton(onClick = onNavigateUp) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "返回")
                    }
                },
                actions = {
                    TextButton(onClick = { /* 保存 */ }) {
                        Text("保存")
                    }
                }
            )

            // 主内容
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
                    .padding(horizontal = 16.dp)
                    .verticalScroll(rememberScrollState())
            ) {
                Spacer(modifier = Modifier.height(8.dp))

                // 交易类型选择 (支出/收入)
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 8.dp)
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(48.dp)
                            .clip(RoundedCornerShape(12.dp))
                            .background(Color(0xFF25252D))
                    ) {
                        // 支出按钮
                        Box(
                            modifier = Modifier
                                .weight(1f)
                                .fillMaxHeight()
                                .clip(
                                    if (uiState.transactionType == TransactionType.EXPENSE)
                                        RoundedCornerShape(12.dp)
                                    else
                                        RoundedCornerShape(0.dp)
                                )
                                .background(
                                    if (uiState.transactionType == TransactionType.EXPENSE)
                                        MaterialTheme.colorScheme.primary
                                    else
                                        Color.Transparent
                                )
                                .clickable { viewModel.setTransactionType(TransactionType.EXPENSE) },
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = "支出",
                                color = if (uiState.transactionType == TransactionType.EXPENSE)
                                    Color.White
                                else
                                    Color.White.copy(alpha = 0.7f),
                                fontWeight = FontWeight.Medium
                            )
                        }

                        // 收入按钮
                        Box(
                            modifier = Modifier
                                .weight(1f)
                                .fillMaxHeight()
                                .clip(
                                    if (uiState.transactionType == TransactionType.INCOME)
                                        RoundedCornerShape(12.dp)
                                    else
                                        RoundedCornerShape(0.dp)
                                )
                                .background(
                                    if (uiState.transactionType == TransactionType.INCOME)
                                        MaterialTheme.colorScheme.primary
                                    else
                                        Color.Transparent
                                )
                                .clickable { viewModel.setTransactionType(TransactionType.INCOME) },
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = "收入",
                                color = if (uiState.transactionType == TransactionType.INCOME)
                                    Color.White
                                else
                                    Color.White.copy(alpha = 0.7f),
                                fontWeight = FontWeight.Medium
                            )
                        }
                    }
                }

                Spacer(modifier = Modifier.height(16.dp))

                // 交易表单
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = Color(0xFF25252D)
                    ),
                    shape = RoundedCornerShape(16.dp)
                ) {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp)
                    ) {
                        // 金额输入区域
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable { showKeyboard = true },
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                "¥",
                                color = Color.White,
                                fontSize = 24.sp,
                                fontWeight = FontWeight.Medium
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text = if (uiState.amount.isEmpty()) "0.00" else uiState.amount,
                                color = Color.White,
                                fontSize = 32.sp,
                                fontWeight = FontWeight.Bold,
                                modifier = Modifier.weight(1f)
                            )
                        }

                        Spacer(modifier = Modifier.height(16.dp))
                        Divider(color = Color.White.copy(alpha = 0.1f))
                        Spacer(modifier = Modifier.height(16.dp))

                        // 日期选择
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable { /* 日期选择器 */ },
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                                imageVector = Icons.Default.DateRange,
                                contentDescription = "日期",
                                tint = Color.White.copy(alpha = 0.7f)
                            )
                            Spacer(modifier = Modifier.width(16.dp))
                            Text(
                                text = "今天",
                                color = Color.White,
                                modifier = Modifier.weight(1f)
                            )
                            Icon(
                                imageVector = Icons.Default.KeyboardArrowRight,
                                contentDescription = "选择",
                                tint = Color.White.copy(alpha = 0.5f)
                            )
                        }

                        Spacer(modifier = Modifier.height(16.dp))
                        Divider(color = Color.White.copy(alpha = 0.1f))
                        Spacer(modifier = Modifier.height(16.dp))

                        // 分类选择
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable { navigateToSelectCategory() },
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                                imageVector = Icons.Default.Category,
                                contentDescription = "分类",
                                tint = Color.White.copy(alpha = 0.7f)
                            )
                            Spacer(modifier = Modifier.width(16.dp))
                            Text(
                                text = if (uiState.selectedCategory == null) "选择分类" else uiState.selectedCategory!!.name,
                                color = Color.White,
                                modifier = Modifier.weight(1f)
                            )
                            Icon(
                                imageVector = Icons.Default.KeyboardArrowRight,
                                contentDescription = "选择",
                                tint = Color.White.copy(alpha = 0.5f)
                            )
                        }

                        Spacer(modifier = Modifier.height(16.dp))
                        Divider(color = Color.White.copy(alpha = 0.1f))
                        Spacer(modifier = Modifier.height(16.dp))

                        // 备注输入
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                                imageVector = Icons.Default.Notes,
                                contentDescription = "备注",
                                tint = Color.White.copy(alpha = 0.7f)
                            )
                            Spacer(modifier = Modifier.width(16.dp))
                            BasicTextField(
                                value = uiState.note,
                                onValueChange = { viewModel.setNote(it) },
                                textStyle = TextStyle(
                                    color = Color.White,
                                    fontSize = 16.sp
                                ),
                                decorationBox = { innerTextField ->
                                    Box {
                                        if (uiState.note.isEmpty()) {
                                            Text(
                                                "添加备注",
                                                color = Color.White.copy(alpha = 0.5f)
                                            )
                                        }
                                        innerTextField()
                                    }
                                },
                                modifier = Modifier.weight(1f)
                            )
                        }
                    }
                }
            }
        }

        // 自定义键盘，单独放在最外层避免布局嵌套问题
        AnimatedVisibility(
            visible = showKeyboard,
            enter = fadeIn(),
            exit = fadeOut(),
            modifier = Modifier.align(Alignment.BottomCenter)
        ) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.BottomCenter
            ) {
                // 半透明背景，点击时关闭键盘
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color.Black.copy(alpha = 0.5f))
                        .clickable { showKeyboard = false }
                )
                
                // 键盘组件
                AmountKeyboard(
                    onKeyPress = { item ->
                        when (item) {
                            is KeyboardItem.Number -> {
                                val currentAmount = uiState.amount
                                if (currentAmount.isEmpty() && item.value == "0") {
                                    return@AmountKeyboard
                                }
                                if (currentAmount.contains(".")) {
                                    val parts = currentAmount.split(".")
                                    if (parts.size > 1 && parts[1].length >= 2) {
                                        return@AmountKeyboard
                                    }
                                }
                                viewModel.setAmount(currentAmount + item.value)
                            }
                            is KeyboardItem.Decimal -> {
                                val currentAmount = uiState.amount
                                if (!currentAmount.contains(".")) {
                                    viewModel.setAmount(
                                        if (currentAmount.isEmpty()) "0." else "$currentAmount."
                                    )
                                }
                            }
                            is KeyboardItem.Delete -> {
                                val currentAmount = uiState.amount
                                if (currentAmount.isNotEmpty()) {
                                    viewModel.setAmount(currentAmount.dropLast(1))
                                }
                            }
                        }
                    },
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }
    }
} 